//
//  DKLoginViewController.swift
//  Sina
//
//  Created by 赵柏清 on 16/7/29.
//  Copyright © 2016年 DarkZhao. All rights reserved.
//

import UIKit
import SVProgressHUD

class DKLoginViewController: UIViewController, UIWebViewDelegate {
    
    let web = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载网页
        loadWeb()
        // 设置导航
        setNAV()
    }
    
    override func loadView() {
        view = web
        web.delegate = self
    }
    
    private func setNAV(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backBtnClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    }
    
    @objc private func backBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func auto(){
        let JS = "document.getElementById('userId').value='zhaoboqing.lan@163.com';document.getElementById('passwd').value='778baiqing1239'"

        web.stringByEvaluatingJavaScriptFromString(JS)
    }
    
    private func loadWeb(){
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2675580399&redirect_uri=http://www.itcast.cn")
        
        let request = NSURLRequest(URL: url!)
        
        web.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

// MARK: - webView的代理方法
extension DKLoginViewController {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let Orequest = request.URL?.absoluteString {
            if Orequest.hasPrefix(redirectUri) {
                if let code = request.URL?.query {
                    let subString = code.substringFromIndex("code=".endIndex)
                        DKLoginViewModel.sharedInstance.getAccessToken(subString, success: { () -> () in
                            
                            
                        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeViewController, object: self)
                            
                        self.dismissViewControllerAnimated(true, completion: nil)
                        SVProgressHUD.dismiss()
                        
                        }, failed: { (error) -> () in
                            printLog("\(error.description)")
                    })
                }
            }
        }
        return true
    }
    
    // 网页开始加载的时候会调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    // 网页加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 网页加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}
